from django.db import models
from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
    phone = models.CharField(max_length=24, verbose_name='手机号')
    img = models.ImageField(upload_to='user', null=True, verbose_name='头像')
    role = models.ForeignKey("users.Role", on_delete=models.SET_NULL, null=True)

    class Meta:
        db_table = 'tb_user'

    def __str__(self):
        return self.username


# 角色
class Role(models.Model):
    title = models.CharField(max_length=24, verbose_name='角色')
    authorization = models.ManyToManyField("users.Authorization", blank=True)
    menus = models.ManyToManyField("users.Menus")

    class Meta:
        db_table = 'tb_role'

    def __str__(self):
        return self.title

    # r = Role.objects.get(id=1)
    # r.authorization.add(1)  r.authorization.remove(1)


class Authorization(models.Model):
    # 权限, 体现在 对url的访问权限上,  /user/   如果我能访问这个url, 那么我就操作用户的权限
    # GET  /user/  POST  PUT DELETE
    desc = models.CharField(max_length=64, verbose_name='权限描述')
    url = models.CharField(max_length=64, verbose_name='地址')
    motheds = models.CharField(max_length=32, verbose_name='请求方法')

    class Meta:
        db_table = 'tb_authorization'

    def __str__(self):
        return self.desc
    # 增加用户,   /user/    post
    # 查询用户,   /user/    get
    # 修改用户,   /user/    put
    # 删除用户,   /user/    delete


class Menus(models.Model):
    label = models.CharField(max_length=24, verbose_name="菜单名")
    parent = models.ForeignKey("self", blank=True, default=None, null=True, on_delete=models.PROTECT,
                               related_name="subs")
    url = models.CharField(max_length=64, verbose_name="菜单地址", blank=True, null=True)

    class Meta:
        db_table = "tb_menus"

    def __str__(self):
        if self.parent:
            return "%s-%s"%(self.parent.label,self.label)
        else:
            return self.label
